package com.security.one_way_encry.sha;

import ch.qos.logback.core.encoder.ByteArrayUtil;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.util.encoders.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @ClassName TestShaBySha1
 * @Description Sha256 算法
 * @Detail detail
 * @Author MyPC
 * @Date 2020/9/23
 * @Version 1.0
 */
public class TestShaBySha256 {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        //2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
        System.out.println(encryptSha256("hello"));
        System.out.println(encryptSha256ByBC("hello"));
    }

    /**
     * 使用JDK的 sha256 加密算法
     * @param key
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String encryptSha256(String key) throws NoSuchAlgorithmException {
        MessageDigest instance = MessageDigest.getInstance("sha-256");
        instance.update(key.getBytes());
        byte[] digest = instance.digest();
        return ByteArrayUtil.toHexString(digest);
    }

    /**
     * 使用 Bouncy Castle 的 sha256 加密算法
     * @param key
     * @return
     */
    public static String encryptSha256ByBC(String key){
        SHA256Digest sha256Digest = new SHA256Digest();
        sha256Digest.update(key.getBytes(),0,key.getBytes().length);
        byte[] bytes=new byte[sha256Digest.getDigestSize()];
        sha256Digest.doFinal(bytes,0);
        return Hex.toHexString(bytes);
    }
}
